package mil.af.amc.adpetracker.web.actions.struts1.ItemModel;

import mil.af.amc.adpetracker.model.ItemModel;
import mil.af.amc.adpetracker.service.ItemModelService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.beans.factory.annotation.Required;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.List;

/**
 * Action to get a list of ItemModels by a given EquipmentType
 *
 * @author TSgt Jason Ferguson
 */

public class GetItemModelByManufacturerAction extends Action {

    private ItemModelService itemModelService;

    @Required
    public void setItemModelService(ItemModelService itemModelService) {
        this.itemModelService = itemModelService;
    }

    @Override
    public ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {

        Integer itemTypeId = (Integer) httpServletRequest.getSession().getAttribute("equipmentTypeId");

        int manufacturerId;

        if (httpServletRequest.getParameter("manufacturerId") == null) {
            manufacturerId = Integer.parseInt(httpServletRequest.getParameter("id"));
        } else {
            manufacturerId = Integer.parseInt(httpServletRequest.getParameter("manufacturerId"));
        }

        List<ItemModel> itemModelList;
        if (itemTypeId!=null) {
            itemModelList = itemModelService.getByEquipmentTypeAndManufacturer(itemTypeId, manufacturerId);
        } else {
            itemModelList = itemModelService.getByManufacturer(manufacturerId);
        }

        Collections.sort(itemModelList);

        JSONArray jsonArray = new JSONArray();
        for (ItemModel model: itemModelList) {
            JSONObject jsonObject = JSONObject.fromObject(model.toMap());
            jsonArray.add(jsonObject);

        }

        httpServletResponse.setHeader("Content-Type", "application/json");
        httpServletResponse.getWriter().println(jsonArray);

        return null;

    }
}
